package com.success.application.base;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.loopj.android.http.TextHttpResponseHandler;
import com.success.application.AppConfig;
import com.success.application.common.result.Result;
import com.success.application.myapplication.R;
import com.success.application.widget.GsonUtils;
import com.success.application.widget.RecyclerRefreshLayout;
import com.success.application.widget.SimplexToast;
import com.success.application.widget.TDevice;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import cz.msebera.android.httpclient.Header;

/**
 * Created by ChrisWong on 2017/1/17.
 */
public abstract class BaseRecyclerViewFragment<T> extends BaseFragment implements
        RecyclerRefreshLayout.SuperRefreshLayoutListener,BaseRecyclerViewAdapter.OnItemClickListener,BaseRecyclerViewAdapter.OnItemLongClickListener {
    protected BaseRecyclerViewAdapter<T> mAdapter;
    protected RecyclerView mRecyclerView;
    protected TextHttpResponseHandler mHandler;
    protected RecyclerRefreshLayout recyclerRefreshLayout;
    protected boolean isRefreshing;
    protected Result<T> result;

    protected int mPageNo;

    /**
     * 提供默认RecyclerView视图
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_base_recycler_view;
    }

    protected abstract BaseRecyclerViewAdapter<T> getRecyclerAdapter();

    protected abstract Type getType();

    protected void initBundle(Bundle bundle){
        super.initBundle(bundle);
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        recyclerRefreshLayout = (RecyclerRefreshLayout) mRoot.findViewById(R.id.refreshLayout);
        mRecyclerView = (RecyclerView) mRoot.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = getRecyclerAdapter();
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        //设置颜色
        recyclerRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
    }

    @Override
    protected void initData() {
        super.initData();
        recyclerRefreshLayout.setSuperRefreshLayoutListener(this);
        mAdapter.setState(BaseRecyclerViewAdapter.STATE_HIDE, false);
        recyclerRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onRefreshing();
                recyclerRefreshLayout.setRefreshing(false);
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState && getActivity() != null
                        && getActivity().getCurrentFocus() != null) {
                    TDevice.hideSoftKeyboard(getActivity().getCurrentFocus());
                }
            }
        });
        // 加载监听器
        mHandler = new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                     result = GsonUtils.fromJson(responseString, getType());
                    if (result != null && result.getRows() != null) {
                        setListData(result);
                        onRequestSuccess(1);
                    } else {
                        mAdapter.setState(BaseRecyclerViewAdapter.STATE_NO_MORE, true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(statusCode, headers, responseString, e);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                onRequestFinish();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                onRequestError();
            }
        };

        onRefreshing();
    }

    protected void onComplete() {
        recyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }

    protected void setListData(Result<T> result) {
        if (isRefreshing) {
            mAdapter.clear();
        } else {
        }
        mAdapter.addAll(result.getRows());
        if (result.getRows() == null || result.getRows().isEmpty() || result.getRows().size() < AppConfig.PAGE_SIZE) {
            mAdapter.setState(BaseRecyclerViewAdapter.STATE_NO_MORE,true);
        }else{
            mAdapter.setState(BaseRecyclerViewAdapter.STATE_LOADING,true);
        }

//        if (mAdapter.getItems().size() > 0) {
//            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
//            mRefreshLayout.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.VISIBLE);
//        } else {
//            mErrorLayout.setErrorType(
//                    isNeedEmptyView()
//                            ? EmptyLayout.NODATA
//                            : EmptyLayout.HIDE_LAYOUT);
//        }
    }

    protected void onRequestSuccess(int code) {

    }

    protected void onRequestFinish() {
        onComplete();
    }

    protected void onRequestError() {
        SimplexToast.show(mContext, "读取数据失败！");
    }

    public void onTabReselect() {
        if (mRecyclerView != null) {
            onRefreshing();
        }
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        mPageNo = 1;
        mRecyclerView.scrollToPosition(0);
        requestData();
    }

    @Override
    public void onLoadMore() {
        //到达最末页不再加载
        if(BaseRecyclerViewAdapter.STATE_NO_MORE != mAdapter.getState()){
            mAdapter.setState(BaseRecyclerViewAdapter.STATE_LOADING, true);
            mPageNo += 1;
            requestData();
        }
    }

    /**
     * 获取服务器数据，初始打开和加载下一页均调用此处，需要处理页码
     */
    protected abstract void requestData();

    @Override
    public void onItemClick(int position, long itemId) {
    }

    @Override
    public void onLongClick(int position, long itemId) {
    }

}
